package com.hank.jms.topic;

import com.hank.common.Constant;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class TopicSenderPersistent {

    public static void main(String[] args) {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Constant.BROKER_URL);
        Connection connection = null;
        try {
            //通过工厂获取一个连接
            connection = connectionFactory.createConnection();

            //通过连接创建一个会话,并默认设开启事务,自动确认消息
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //通过会话构建一个目的地
            Destination destination = session.createTopic("persistent_topic");
            /* 再通过session创建一个消息发送者，并设定发送目的地对象 */
            MessageProducer messageProducer = session.createProducer(destination);
            messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
            connection.start();
            for (int i = 0; i < 3; i++) {
                TextMessage message = session.createTextMessage("This is Topic TextMessage >>" + i);
                messageProducer.send(message);
            }
            session.commit();
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
